package com.xyz.common.intercepter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.xyz.business.bean.User;
import com.xyz.constant.XYZConstant;
import com.xyz.util.IPAuthentication;

public class UserLoginInterceptor implements Interceptor {
	/**
	 * 序列号
	 */
	private static final long serialVersionUID = -8493212520848227644L;
	/**
	 * 日志类
	 */
	static Logger logger = Logger.getLogger(UserLoginInterceptor.class);
	/**
	 * 白名单
	 */
	static String white_urls = XYZConstant.EMPTY;

	@Override
	public void destroy() {

	}

	@Override
	public void init() {

	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		logger.info("权限拦截功能..");
		HttpServletRequest request = ServletActionContext.getRequest();
		// 白名单校验
		String result = "";

		// ip权限校验
		if (IPAuthentication.havaPri(request)) {

			if (StringUtils.isBlank(white_urls)) {
				white_urls = ServletActionContext.getServletContext()
						.getInitParameter("WhiteURL");
			}

			// 判断当前请求的url有没有在白名单中
			if (checkRequestURIIntNotFilterList(request)) {
				// User user = (User)
				// request.getSession().getAttribute("login_user");
				// if (user == null) {
				// result = "error";
				// } else {
				// result = invocation.invoke();
				// }
				result = invocation.invoke();

			} else {
				// 当前要调用的不是登录的Action
				// 从session中取值，判断是否是空（登录）
				Map session = invocation.getInvocationContext().getSession();
				if (session == null) {
					result = "error";
				} else {
					User user = (User) session.get("login_user");
					if (null == user) {
						result = "error";
					} else {
						result = invocation.invoke();
					}

				}

			}
		} else {
			result = "nopurview";
		}
		return result;
	}

	private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
		String uri = request.getRequestURI();
		int index = uri.lastIndexOf("/");
		int len = uri.length();
		if (index == len) {
			// 有可能是/user/这种请求
			uri = XYZConstant.EMPTY;
		} else {
			uri = uri.substring(index + 1);
		}
		String temp = request.getRequestURI();
		temp = temp.substring(request.getContextPath().length() + 1);
		// System.out.println("是否包括："+uri+";"+notCheckURLList+"=="+notCheckURLList.contains(uri));
		return white_urls.contains(uri);
	}
}
